﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using UCHENG.FILEHASH.UTILS.ADB;

namespace UCHENG.FILEHASH.UTILS
{
    public class DownloadService
    {
        public event EventHandler<EventArgs> TeacherPlayerDownLoadCompleteEventHandler;

        public event EventHandler<EventArgs> StudentPlayerDownLoadCompleteEventHandler;

        //delegate void DownLoadCompleteDelegate(string str)

        //    event MyDele MyEvent;　　//定义事件

        public void Excute(PlayerVo playerVo)
        {

            var jsonText = HttpService.getPlayerUrl(playerVo.PlayerCode, playerVo.PlayerVersion);
            List<Player> list = JsonConvert.DeserializeObject<List<Player>>(jsonText);
            foreach (var item in list)
            {
                string url = item.url;
                Uri uri = new Uri(url);
                string queryString = uri.Query;
                NameValueCollection nameValueCollection = GetQueryString(queryString);
                string name = nameValueCollection["name"];

                System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
                stopwatch.Start();
                MessageService.start(playerVo.PlayerCode + item.description + " Player  ：" + name);

                string path = getZipPlayerName(queryString);

                using (FileStream fs = new FileStream(
                    path,
                    FileMode.OpenOrCreate,
                    FileAccess.Write,
                    FileShare.Read,
                    2048,
                    FileOptions.RandomAccess
                    ))
                {
                    //先下载文件的第100个字节到最后
                    fs.Seek(100, SeekOrigin.Begin);
                    Down(fs, url, 100);

                    //下载前100个字节
                    fs.Seek(0, SeekOrigin.Begin);
                    Down(fs, url, 0, 99);
                }

                MessageService.end(playerVo.PlayerCode + item.description + " Player ：" + name, stopwatch.Elapsed.TotalSeconds);
                stopwatch.Stop();

                if (!path.Contains("student"))
                {
                    ZipService.Excute(System.Environment.CurrentDirectory + "\\" + path, playerVo.PlayerPath, playerVo.IsReplace);
                    File.Delete(playerVo.PlayerPath + "\\" + path);
                }

                if (path.Contains("student") && !string.IsNullOrEmpty(playerVo.DeviceId) && playerVo.IsReplacePhone)
                {
                    AdbHelper.CopyFileToDevice(playerVo.DeviceId, System.Environment.CurrentDirectory + "\\" + path, playerVo.PhonePlayerPath);
                    File.Delete(System.Environment.CurrentDirectory + "\\" + path);
                    //ZipService.Excute(System.Environment.CurrentDirectory + "\\" + path, playerVo.PlayerPath, true);
                    //AdbHelper.CopyDirToDevice(playerVo.DeviceId, playerVo.PlayerPath + "\\" + Path.GetFileNameWithoutExtension(path), playerVo.PhonePlayerPath + Path.GetFileNameWithoutExtension(path));
                    //Directory.Delete(playerVo.PlayerPath + "\\" + path);
                }
            }
        }

        public string getZipPlayerName(string queryString)
        {
            string path = "player.zip";
            if (queryString.Contains("_student_"))
            {
                path = "player_student.zip";
            }
            return path;
        }

        public void Down(FileStream fs, string url, int start, int end = -1)
        {
            HttpWebRequest hwr = WebRequest.Create(url) as HttpWebRequest;
            if (end == -1)
                hwr.AddRange(start);
            else
                hwr.AddRange(start, end);
            HttpWebResponse resp = hwr.GetResponse() as HttpWebResponse;
            using (Stream input = resp.GetResponseStream())
            {
                byte[] bs = new byte[2048];
                int count;
                while ((count = input.Read(bs, 0, bs.Length)) != 0)
                {
                    fs.Write(bs, 0, count);
                }
            }
        }

        /// <summary>
        /// 将查询字符串解析转换为名值集合.
        /// </summary>
        /// <param name="queryString"></param>
        /// <returns></returns>
        private static NameValueCollection GetQueryString(string queryString)
        {
            return GetQueryString(queryString, null, true);
        }

        /// <summary>
        /// 将查询字符串解析转换为名值集合.
        /// </summary>
        /// <param name="queryString"></param>
        /// <param name="encoding"></param>
        /// <param name="isEncoded"></param>
        /// <returns></returns>
        private static NameValueCollection GetQueryString(string queryString, Encoding encoding, bool isEncoded)
        {
            queryString = queryString.Replace("?", "");
            NameValueCollection result = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
            if (!string.IsNullOrEmpty(queryString))
            {
                int count = queryString.Length;
                for (int i = 0; i < count; i++)
                {
                    int startIndex = i;
                    int index = -1;
                    while (i < count)
                    {
                        char item = queryString[i];
                        if (item == '=')
                        {
                            if (index < 0)
                            {
                                index = i;
                            }
                        }
                        else if (item == '&')
                        {
                            break;
                        }
                        i++;
                    }
                    string key = null;
                    string value = null;
                    if (index >= 0)
                    {
                        key = queryString.Substring(startIndex, index - startIndex);
                        value = queryString.Substring(index + 1, (i - index) - 1);
                    }
                    else
                    {
                        key = queryString.Substring(startIndex, i - startIndex);
                    }
                    if (isEncoded)
                    {
                        result[MyUrlDeCode(key, encoding)] = MyUrlDeCode(value, encoding);
                    }
                    else
                    {
                        result[key] = value;
                    }
                    if ((i == (count - 1)) && (queryString[i] == '&'))
                    {
                        result[key] = string.Empty;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 解码URL.
        /// </summary>
        /// <param name="encoding">null为自动选择编码</param>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string MyUrlDeCode(string str, Encoding encoding)
        {
            if (encoding == null)
            {
                Encoding utf8 = Encoding.UTF8;
                //首先用utf-8进行解码                     
                string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
                //将已经解码的字符再次进行编码.
                string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
                if (str == encode)
                    encoding = Encoding.UTF8;
                else
                    encoding = Encoding.GetEncoding("gb2312");
            }
            return HttpUtility.UrlDecode(str, encoding);
        }
    }
}
